//
//  COEditProController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import UIKit
import TZImagePickerController

class COEditProController: COBaseController {

    lazy var containView: UIView = {
        let con = UIView()
        con.backgroundColor = .white
        return con
    }()
    
    let titleArr = ["Photo","Username","Age","Gender"]
    
    lazy var baseTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = .clear
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.contentInset = UIEdgeInsets(top: PTW(10), left: 0, bottom: 0, right: 0)
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 11.0, *) {
            if #available(iOS 13.0, *) {
                tableView.automaticallyAdjustsScrollIndicatorInsets = false
            }else{
                tableView.contentInsetAdjustmentBehavior = .never
            }
        }else {
            automaticallyAdjustsScrollViewInsets = false
        }
        return tableView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.addnav()
        self.title = "Your Profile"
        setUI()
    }
    
    // 设置UI
    func setUI(){
        self.view.addSubview(self.containView)
        self.containView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.navView.snp.bottom)
        }
        self.containView.addSubview(self.baseTableView)
        self.baseTableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.navView.snp.bottom)
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.containView.clipsCorners(corners: [.topLeft,.topRight], radius: PTW(30))
    }
}

extension COEditProController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.titleArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = COUserInfoManager.shared.curUser
        let cell = COEditProfileViewCell().cellWithTableView(tableView)
        cell.selectionStyle = .none
        cell.leftLbl.text = self.titleArr[indexPath.row]
        if(indexPath.row == 0){
            cell.iconImg.isHidden = false
            cell.rightLbl.isHidden = true
            cell.iconImg.sd_setUrlImage(model?.userResponse.profilePhoto, placeholder: KImaged("coco_icon_holder"))
            cell.bottomLine.isHidden = false
        }else if(indexPath.row == 1){
            cell.iconImg.isHidden = true
            cell.rightLbl.isHidden = false
            cell.rightLbl.text = model?.userResponse.nickName
            cell.bottomLine.isHidden = false
        }else if(indexPath.row == 2){
            cell.iconImg.isHidden = true
            cell.rightLbl.isHidden = false
            cell.bottomLine.isHidden = false
            let age = model?.userResponse.age
            if(age ?? 0 < 18){
                cell.rightLbl.text = "18"
            }else{
                cell.rightLbl.text = "\(age!)"
            }
        }else if(indexPath.row == 3){
            cell.iconImg.isHidden = true
            cell.rightLbl.isHidden = false
            cell.bottomLine.isHidden = true
            //性别 0男,1女,2LadyBoy
            let gender = model?.userResponse.gender
            if(gender == 0){
                cell.rightLbl.text = "Male"
            }else{
                cell.rightLbl.text = "Female"
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return PTW(80)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0{
            DispatchQueue.main.safeAsync({
                let pick = TZImagePickerController(maxImagesCount: 1, delegate: self)!
                self.present(pick, animated: true)
            })
        }else if indexPath.row == 1{
            let vc = COEdditNameController()
            self.navigationController?.pushViewController(vc, animated: true)
            vc.nameEditBlock = { [weak self] name in
                self?.changeUserInfo(avatar: nil, nickname: name, age: nil, gender: nil)
            }
        }else if indexPath.row == 2{
            var dataSource = [String]()
            for i in 18...80 {
                dataSource.append("\(i)")
            }
            let agePicker = COPickerView(frame: self.view.bounds, dataSource: dataSource)
            agePicker.pickerSelectClosure = { [weak self] title in
                let age = Int(title)
                self?.changeUserInfo(avatar: nil, nickname: nil, age: age, gender: nil)
            }
            agePicker.showIn(view: self.view)
        }else if indexPath.row == 3{
            let genderPicker = COPickerView(frame: self.view.bounds, dataSource: ["Male", "Female"])
            genderPicker.pickerSelectClosure = { [weak self] title in
                self?.changeUserInfo(avatar: nil, nickname: nil, age: nil, gender: title == "Male" ? 0 : 1)
            }
            genderPicker.showIn(view: self.view)
        }
    }
    
    func changeUserInfo(avatar: String?, nickname: String?, age: Int?, gender: Int?){
        var params = [String: Any]()
        var user = COUserInfoManager.shared.curUser
        params["id"] = user?.userResponse.id
        if avatar != nil {
            params["profilePhoto"] = avatar!
            user?.userResponse.profilePhoto = avatar!
        }else {
            params["profilePhoto"] = user?.userResponse.profilePhoto
        }
        if nickname != nil {
            params["nickName"] = nickname!
            user?.userResponse.nickName = nickname!
        }else {
            params["nickName"] = user?.userResponse.nickName
        }
        if gender != nil {
            params["gender"] = gender!
            user?.userResponse.gender = gender!
        }else {
            params["gender"] = user?.userResponse.gender
        }
        if age != nil {
            params["age"] = age!
            user?.userResponse.age = age!
        }else {
            params["age"] = user?.userResponse.age
        }
        COHttpManager.request(target: COBaseApi.editUser(param: params), modelType: CONSObjectModel.self) {code, object, success in
            if (avatar?.isEmptyStr == false){
                UIToolHelper.makeToast("Edit successfully!")
            }
            COUserInfoManager.shared.curUser = user
            COUserInfoManager.coSaveInfo()
            let curmodel = COUserInfoManager.shared.curUser
            RCIM.shared().refreshUserInfoCache(RCUserInfo(userId: curmodel!.rcUserId, name: curmodel?.userResponse.nickName, portrait: curmodel?.userResponse.profilePhoto), withUserId: curmodel!.rcUserId)
            self.baseTableView.reloadData()
        } failureBlock: { code, msg in
        }
    }
}

extension COEditProController: TZImagePickerControllerDelegate {
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        self.view.endEditing(true)
        let img = photos.first
        changeMyAvater(img)
    }
    
    // 上传头像
    func changeMyAvater(_ image:UIImage?){
        let uploadImageData = compressImageToData(image)
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.uploadData(data: uploadImageData ?? Data.init()), modelType: UploadResponseModel.self) {[weak self] code, object, success in
            UIToolHelper.hideHUD()
            self?.changeUserInfo(avatar: object?.url, nickname: nil, age: nil, gender: nil)
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
        }
    }
    
    func compressImageToData(_ img:UIImage?) -> Data? {
        var data = img?.jpegData(compressionQuality: 1.0)
        if (data?.count ?? 0) > 100 * 1024 {
            if (data?.count ?? 0) > 1024 * 1024 {
                //1M以及以上
                data = img?.jpegData(compressionQuality: 0.1)
            } else if (data?.count ?? 0) > 512 * 1024 {
                //0.5M-1M
                data = img?.jpegData(compressionQuality: 0.5)
            } else if (data?.count ?? 0) > 200 * 1024 {
                //0.25M-0.5M
                data = img?.jpegData(compressionQuality: 0.9)
            }
        }
        return data
    }
}
